package cn.iclass.modules.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.iclass.common.constant.RedisKeys;
import cn.iclass.common.utils.Result;
import cn.iclass.modules.sys.oauth2.TokenGenerator;
import cn.iclass.modules.sys.service.RedisService;
import cn.iclass.modules.sys.service.SysUserTokenService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description: 用户token
 * @Author: alan
 * @Date: 2019/6/10 5:22 PM
 */
@Service("sysUserTokenService")
public class SysUserTokenServiceImpl implements SysUserTokenService {
	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 12;

	@Resource
	private RedisService redisService;


	@Override
	public Result createToken(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();
		redisService.set(RedisKeys.SYS_USER_TOKEN + token, userId + "", EXPIRE);
		Map<String, Object> result = new HashMap<>(2);
		result.put("token", token);
		result.put("expire", EXPIRE);
		return Result.ok(result);
	}


	@Override
	public Long queryUserIdByToken(String token) {
		Object userId = redisService.get(RedisKeys.SYS_USER_TOKEN + token);
		if (ObjectUtil.isNull(userId)) {
			return null;
		} else {
			return Long.valueOf(String.valueOf(userId));
		}
	}

	/**
	 * logout
	 *
	 * @param token
	 * @return void
	 * @Author alan
	 * @Date 2019/7/5 2:09 PM
	 */
	@Override
	public void logout(String token) {
		redisService.del(RedisKeys.SYS_USER_TOKEN + token);
		SecurityUtils.getSubject().logout();
	}
}
